<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：已接任务控制器。
 *
 **/
namespace Api\Controller;
use Think\Upload;
class UploadController extends ComController
{ 
  
    /**
     * 上传图片接口
     */
    public function index()
    {
        if ($_FILES['file']) {
            $upload = new Upload(array(
                'exts' => array('jpg', 'gif', 'png', 'jpeg','bmp','application/octet-stream'),
                'rootPath' => './Public/',
                'savePath' => 'attached/'.date('Y')."/".date('m')."/",
                'subName'  =>  array('date', 'd'),
                'maxSize' => $maxSize,
                'autoSub' => true
            ));
            
            
            $info = $upload->uploadOne($_FILES['file']);
            if(!$info) {// 上传错误提示错误信息
                $error = $upload->getError();
                $this->res['code'] = 100;
                $this->res['msg'] = $error;
                $this->response($this->res,'json');
            }else{// 上传成功
                $ImgStr = C('URL')."/Public/".$info['savepath'].$info['savename'];
                $saveDbUrl = "/Public/".$info['savepath'].$info['savename'];
                $imgData = array(
                    'imgShowUrl'=>$ImgStr,
                    'saveDbUrl'=>$saveDbUrl
                );
                $this->res['code'] = 200;
                $this->res['msg'] = '上传成功';
                $this->res['data'] = $imgData;
                $this->response($this->res,'json');
            }
        }
    }
    
    
    /**
     * 接收流文件
     * @param unknown $receiveFile
     * @return boolean|number
     */
    private function receiveStreamFile($receiveFile){
        $streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
        
        if(empty($streamData)){
            $streamData = file_get_contents('php://input');
        }
        
        if($streamData!=''){
            $ret = file_put_contents($receiveFile, $streamData, true);
            var_dump($ret);
        }else{
            $ret = false;
        }
        return $ret;
    } 
    
    /**
     * base64传输图片
     * @param unknown $base64_image_content
     */
    public function saveBase64Image(){
        if(!IS_POST){
            $this->res['code'] = 100;
            $this->res['msg'] = '请用post方法请求接口';
            $this->response($this->res,'json');
        }
        $post_data = file_get_contents('php://input');
        $json = json_decode($post_data);
        $base64_image_content = $json->base64_image_content;
        
        
        if(!$base64_image_content){
            $this->res['code'] = 100;
            $this->res['msg'] = '传输内容为空';
            $this->response($this->res,'json');
        }
        //$this->write_log($base64_image_content);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result) || preg_match('/^(data:application\/octet-stream;base64,)/', $base64_image_content, $result)){
            //图片后缀
            $type = $result[2];
            if(!$type){
                $type = 'jpg';
            }
            //保存位置--图片名
            $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
            //$this->write_log('文件名：'.$image_name);
            $rootPath = './Public/';
            $image_file_path = 'attached/'.date('Y')."/".date('m');
            $image_file = __ROOT__.$rootPath.$image_file_path;
            $imge_real_url = $image_file.'/'.$image_name;
            $imge_web_url = '/Public/'.$image_file_path.'/'.$image_name;
            if (!file_exists($image_file)){
                mkdir($image_file, 0700);
                fopen($image_file.'\\'.$image_name, "w");
            }
            //解码
            $decode=base64_decode(str_replace($result[1], '', $base64_image_content));
            if (file_put_contents($imge_real_url, $decode)){
                $imgData = array(
                    'imgShowUrl'=>C('URL').$imge_web_url,
                    'saveDbUrl'=>$imge_web_url
                );
                $this->res['code'] = 200;
                $this->res['msg'] = '上传成功';
                $this->res['data'] = $imgData;
                $this->response($this->res,'json');
            }else{
                $this->res['code'] = 100;
                $this->res['msg'] = '上传失败';
                $this->response($this->res,'json');
            }
        }else{
            $this->res['code'] = 100;
            $this->res['msg'] = '图片格式错误';
            $this->response($this->res,'json');
        }
    }
    
    private function write_log($data){
        $years = date('Y-m');
        //设置路径目录信息
        $url = './Public/log/txlog/'.$years.'/'.date('Ymd').'_request_log.txt';
        $dir_name=dirname($url);
        //目录不存在就创建
        if(!file_exists($dir_name))
        {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        fwrite($fp,var_export($data,true)."\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }
}